/* 战斗成员 */
const Net_battleMembers = Game_Party.prototype.battleMembers;
Game_Party.prototype.battleMembers = function () {
    if (NetManager.battleMode === "input" && NetManager.battleData) {
        const num = NetManager.battleData.length;
        const member = [];
        for (let i = 0; i < num; i++) {
            const id = i + 5;
            member.push($gameActors.actor(id));
        }
        return member;
    }
    return Net_battleMembers.call(this);
}

//战斗结束复原随机模式
const Net_updateBattleEnd = BattleManager.updateBattleEnd;
BattleManager.updateBattleEnd = function () {
    Net_updateBattleEnd.call(this);
    NetManager.battleMode = "default";
    NetManager.randomSeed = 114514;
}

const Net_Battle_initialize = Scene_Battle.prototype.initialize;
Scene_Battle.prototype.initialize = function () {
    Net_Battle_initialize.call(this);
    NetMap.needPlacePlayer = true;
}

//倒计时
const Net_Battle_createDisplayObjects = Scene_Battle.prototype.createDisplayObjects;
Scene_Battle.prototype.createDisplayObjects = function () {
    Net_Battle_createDisplayObjects.call(this);
    if (NetManager.battleMode === "input") {
        this.createTimeSprite();
    }
}

Scene_Battle.prototype.createTimeSprite = function () {
    const sprite = new Sprite_Countdown();
    const x = (Graphics.boxWidth - 100) / 2;
    const y = (Graphics.boxHeight - 100) / 2;
    sprite.hide();
    sprite.move(x, y);
    this.addChild(sprite);
    this._countdown = sprite;
}

/* 选择下一个角色 */
BattleManager.selectNextActor = function () {
    this.changeCurrentActor(true);
    if (!this._currentActor) {
        if (this.isTpb()) {
            this.changeCurrentActor(true);
        } else {
            if (NetManager.battleMode === "input") {
                return;
            }
            this.startTurn();
        }
    }
}

/* 切换当前角色 */
BattleManager.changeCurrentActor = function (forward) {
    const name = NetManager.actorMapData.name;
    const members = $gameParty.battleMembers();
    let actor = this._currentActor;
    for (; ;) {
        const currentIndex = members.indexOf(actor);
        actor = members[currentIndex + (forward ? 1 : -1)];
        if (!actor || (actor.canInput() && actor._name === name)) {
            break;
        }
    }
    this._currentActor = actor ? actor : null;
    this.startActorInput();
}

/* 开始角色输入 */
BattleManager.startActorInput = function () {
    if (this._currentActor) {
        // if (this._currentActor._name != NetManager.actorMapData.name) {
        //     this.selectNextActor();
        //     return;
        // }
        this._currentActor.setActionState("inputting");
        this._inputting = true;
        if (NetManager.battleMode === "input") {
            SceneManager._scene._countdown.start();
        }
    }
}

/* 选择下一个命令 */
BattleManager.selectNextCommand = function () {
    if (this._currentActor) {
        if (this._currentActor.selectNextCommand()) {
            return;
        }
        this.finishActorInput();
    }
    this.selectNextActor();
};

/* 当角色确定 */
Scene_Battle.prototype.onActorOk = function () {
    if (NetManager.battleMode === "input") {
        NetManager.battleAction["index"] = this._actorWindow.index();
        NetManager.battleServer.emit("battle input", NetManager.battleAction);
        NetManager.battleAction = {};
        NetManager.battleAction["name"] = NetManager.actorMapData.name;
        BattleManager._inputting = false;
        // SceneManager._scene.endCommandSelection();
    } else {
        const action = BattleManager.inputtingAction();
        action.setTarget(this._actorWindow.index());
    }
    this.hideSubInputWindows();
    this.selectNextCommand();
};

/* 当敌人确定 */
Scene_Battle.prototype.onEnemyOk = function () {
    if (NetManager.battleMode === "input") {
        NetManager.battleAction["index"] = this._enemyWindow.enemyIndex();
        NetManager.battleServer.emit("battle input", NetManager.battleAction);
        NetManager.battleAction = {};
        NetManager.battleAction["name"] = NetManager.actorMapData.name;
        BattleManager._inputting = false;
        // SceneManager._scene.endCommandSelection();
    } else {
        const action = BattleManager.inputtingAction();
        action.setTarget(this._enemyWindow.enemyIndex());
    }
    this.hideSubInputWindows();
    this.selectNextCommand();
};

/* 攻击的指令 */
Scene_Battle.prototype.commandAttack = function () {
    const action = BattleManager.inputtingAction();
    if (NetManager.battleMode === "input") {
        NetManager.battleAction["type"] = "skill";
        NetManager.battleAction["itemId"] = action.subject().attackSkillId();
    }
    action.setAttack();
    this.onSelectAction();
};

/* 当技能确定 */
Scene_Battle.prototype.onSkillOk = function () {
    const skill = this._skillWindow.item();
    if (NetManager.battleMode === "input") {
        NetManager.battleAction["type"] = "skill";
        NetManager.battleAction["itemId"] = skill.id;
    } //else {
    const action = BattleManager.inputtingAction();
    action.setSkill(skill.id);
    BattleManager.actor().setLastBattleSkill(skill);
    // }
    this.onSelectAction();
};

/* 当物品确定 */
Scene_Battle.prototype.onItemOk = function () {
    const item = this._itemWindow.item();
    if (NetManager.battleMode === "input") {
        NetManager.battleAction["type"] = "item";
        NetManager.battleAction["itemId"] = skill.id;
    }
    const action = BattleManager.inputtingAction();
    action.setItem(item.id);
    $gameParty.setLastItem(item);
    this.onSelectAction();
};

/* 当选择行动 */
Scene_Battle.prototype.onSelectAction = function () {
    const action = BattleManager.inputtingAction();
    if (!action.needsSelection()) {
        if (NetManager.battleMode === "input") {
            NetManager.battleServer.emit("battle input", NetManager.battleAction);
            NetManager.battleAction = {};
            NetManager.battleAction["name"] = NetManager.actorMapData.name;
            BattleManager._inputting = false;
        }
        this.selectNextCommand();
    } else if (action.isForOpponent()) {
        this.startEnemySelection();
    } else {
        this.startActorSelection();
    }
};

class NetBattle {
    //创建socket事件，将在选择角色进入游戏后执行
    static createSocketEvent() {

        const socket = NetManager.battleServer;

        //战斗
        socket.on("battle start", (id) => {
            // NetManager.randomMode = "seed";
            // NetManager.randomSeed = seed;
            // NetManager.battleData = data;
            // NetManager.battleMode = "input";
            // NetManager.battleAction["name"] = NetManager.actorMapData.name;
            // const battleMember = $gameParty.battleMembers();
            // for (let i = 0; i < battleMember.length; i++) {
            //     battleMember[i].setupNetBattle(data[i]);
            // }
            // $gameTemp.battleCount = $gameParty.battleMembers().length;
            BattleManager.setup(id, true, false);
            BattleManager.onEncounter();
            SceneManager.push(Scene_Battle);
        })

        //战斗指令输入
        socket.on("battle player input", (data) => {
            if ($gameParty.inBattle()) {
                const { name, index, type, itemId } = data;
                const actor = NetManager.battleActor[name];
                const action = actor.action(0);
                action.setTarget(index);
                if (type === "skill") {
                    action.setSkill(itemId);
                } else if (type === "item") {
                    action.setItem(itemId);
                }
                $gameTemp.battleCount--;
                if ($gameTemp.battleCount === 0) {
                    BattleManager.startTurn();
                    $gameTemp.battleCount = $gameParty.battleMembers().length;
                }
            }
        })
    }

    //战斗
    static netBattle(troopId) {
        if (NetManager.party) {
            const name = NetManager.actorMapData.name;
            if (name != NetManager.party[name].leader) {
                SceneManager._scene._mapNameWindow.pop("组队状态下，只有队长才可以操作！");
                return;
            }
            const battleId = `${name}${Date.now()}`;
            //暂时使用队伍所有在线成员，后续根据准备状态确定进入战斗的成员
            const member = Object.keys(NetManager.party).filter(item => { return NetManager.party[item] != null });
            const data = { battleId, member, troopId }
            NetManager.battleServer.emit("create", data, () => {
                NetManager.mapServer.emit("battle", data);
            })
        }
    }

    //加入战斗
    static joinBattle(battleData) {
        const { battleId } = battleData;
        const name = NetManager.actorMapData.name;
        const data = { battleId, name }
        NetManager.battleServer.emit("join", data)
    }
}

class Sprite_Countdown extends Sprite {
    initialize() {
        super.initialize();
        this.createBitmap();
        this._time = 0;
    }

    createBitmap() {
        const bitmap = new Bitmap(100, 100);
        bitmap.fontFace = $gameSystem.mainFontFace();
        bitmap.fontSize = 75;
        // bitmap.textColor = this.labelColor();
        this.bitmap = bitmap;
    }

    start() {
        this._time = Date.now() + 30000;
        this.show();
    }

    update() {
        super.update();
        this.updateTime();
    }

    updateTime() {
        const time = Math.floor((this._time - Date.now()) / 1000);
        this.bitmap.clear();
        this.bitmap.drawText(time, 0, 0, 100, 100, "center");
    }
}